package org.opens.mybatisplus.controller.page;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.opens.mybatisplus.pojo.dto.MyBatisPerson;
import org.opens.mybatisplus.service.MybatisPersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
public class ThymeleafPageController {

    @Autowired
    private MybatisPersonService mybatisPersonService;

    @Autowired
    private ObjectMapper objectMapper;

    @RequestMapping(value = "/thymeleaf/th")
    public ModelAndView goPage(
            @RequestParam(value = "id", required = false, defaultValue = "4") Integer id
    ) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("thymeleaf/th");
        if(id != null) {
            try {
                MyBatisPerson person = mybatisPersonService.findById(id);
                modelAndView.addObject("person", person);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        modelAndView.addObject("today", new Date());
        return modelAndView;
    }

    @RequestMapping(value = "/thymeleaf/footer")
    public ModelAndView goFooterPage(
            @RequestParam(value = "id", required = false, defaultValue = "4") Integer id
    ) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("thymeleaf/footer");
        modelAndView.addObject("today", new Date());
        return modelAndView;
    }

    @RequestMapping(value = "/thymeleaf/objectToJs")
    public ModelAndView goObjectToJs() throws JsonProcessingException {
        Map<String, Object> map = new HashMap<>();
        map.put("name", "s1");
        map.put("age", "21");
        map.put("address", Arrays.asList(1, 2, 3, 4, 5));
        ModelAndView modelAndView = new ModelAndView("thymeleaf/objectToJs");
        modelAndView.addObject("data", objectMapper.writeValueAsString(map));
        return modelAndView;
    }

}
